/*
 *  Copyright 2010 Mahbub Mozadded Sowrov.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

/*
 * SettingWindow.java
 *
 * Created on Oct 18, 2010, 7:10:52 AM
 */

package com.sowrov.afrigis.tools.app.timesheet_manager;

import com.sowrov.afrigis.tools.sqlite.DatabaseManager;
import com.sowrov.afrigis.tools.timesheet.Project;
import com.sowrov.afrigis.tools.timesheet.TimeSheetClient;
import com.sowrov.afrigis.tools.timesheet.User;
import com.sowrov.afrigis.tools.timesheet.parse.html.ParseSubmitPage;
import com.sowrov.util.logsystem.ChronicleLogger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Sowrov
 */
public class SettingWindow extends javax.swing.JDialog {
    private DatabaseManager dbManager = null;
    private User user = null;
    private String userName, passWord, urlStr, portStr, intervalStr;
    private TaskManagerView parent;
    /** Creates new form SettingWindow */
    public SettingWindow(TaskManagerView parent, boolean modal, User user, DatabaseManager dbManager) {
        super(parent!=null?parent.getFrame():null, modal);
        this.parent = parent;
        initComponents();
        this.user = user;
        this.dbManager = dbManager;
//        this.setLocationRelativeTo(parent.getFrame());
        updateComponetsFromDB();
    }

    public void setUser(User user) {
        this.user = user;
        this.updateComponetsFromDB();
    }

    public User getUser() {
        return user;
    }
    
    public void setDatabaseManager(DatabaseManager dbManager) {
        this.dbManager = dbManager;
    }

    private void updateInfo() {
        this.urlStr = this.urlBox.getText().trim();
        this.portStr = this.portBox.getText().trim();
        if (this.portStr.equals("")) {
            this.portStr = "80";
            this.portBox.setText("80");
        }
        this.userName = this.userNameBox.getText();
        char[] passArray = this.passwordBox.getPassword();
        StringBuilder pass = new StringBuilder();
        for (int i=0; i<passArray.length; i++) {
            pass.append(passArray[i]);
        }
        this.passWord = pass.toString();

        this.intervalStr = this.intervalSlide.getValue() + "";
    }

    public void setVisible() {
        this.setLocationRelativeTo(parent.getFrame());
        this.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        portBox = new javax.swing.JTextField();
        urlBox = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        userNameBox = new javax.swing.JTextField();
        passwordBox = new javax.swing.JPasswordField();
        updateButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        paTree = new javax.swing.JTree();
        jLabel5 = new javax.swing.JLabel();
        intervalSlide = new javax.swing.JSlider();
        saveButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Settings");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("TimeSheet Site"));
        jPanel2.setName("jPanel2"); // NOI18N

        jPanel3.setName("jPanel3"); // NOI18N

        jLabel3.setText("Address :");
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText("Port:");
        jLabel4.setName("jLabel4"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setName("jPanel4"); // NOI18N

        portBox.setText("80");
        portBox.setName("portBox"); // NOI18N

        urlBox.setText("196.35.231.10");
        urlBox.setName("urlBox"); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(portBox, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
                    .addComponent(urlBox, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(urlBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(portBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("personal"));
        jPanel1.setName("jPanel1"); // NOI18N

        jPanel5.setName("jPanel5"); // NOI18N

        jLabel1.setText("User Name:");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText("Password  :");
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel6.setText("Project     :");
        jLabel6.setName("jLabel6"); // NOI18N

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel6))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(77, 77, 77)
                .addComponent(jLabel6)
                .addContainerGap(99, Short.MAX_VALUE))
        );

        jPanel6.setName("jPanel6"); // NOI18N

        userNameBox.setName("userNameBox"); // NOI18N

        passwordBox.setName("passwordBox"); // NOI18N

        updateButton.setText("Check user validity and update project information");
        updateButton.setName("updateButton"); // NOI18N
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Project");
        javax.swing.tree.DefaultMutableTreeNode treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("node 2");
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Project2");
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("n2");
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        paTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        paTree.setName("paTree"); // NOI18N
        paTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                paTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(paTree);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(userNameBox, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordBox, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(updateButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(userNameBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(passwordBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(updateButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jLabel5.setText("Notification Interval (hour):");
        jLabel5.setName("jLabel5"); // NOI18N

        intervalSlide.setMajorTickSpacing(1);
        intervalSlide.setMaximum(12);
        intervalSlide.setMinorTickSpacing(1);
        intervalSlide.setPaintLabels(true);
        intervalSlide.setPaintTicks(true);
        intervalSlide.setSnapToTicks(true);
        intervalSlide.setValue(2);
        intervalSlide.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        intervalSlide.setName("intervalSlide"); // NOI18N

        saveButton.setText("Save");
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        closeButton.setText("Close");
        closeButton.setName("closeButton"); // NOI18N
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(intervalSlide, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(intervalSlide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(closeButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void paTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_paTreeValueChanged
        TreePath tpath = evt.getPath();
}//GEN-LAST:event_paTreeValueChanged

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        this.updateInfo();

        if (this.urlStr.equals("") || this.userName.equals("") || this.passWord.equals("")) {
            JOptionPane.showMessageDialog(this, "Please fill all the text boxes with appropiate data.");
            return;
        }
        this.parent.showLoading("Saving...", this);
        new Thread(new Runnable() {
            public void run() {
                ArrayList<String> value = new ArrayList<String>();
                value.add("1");
                value.add(userName);
                value.add(passWord);
                value.add(urlStr);
                value.add(portStr);
                value.add(intervalStr);
                value.add("0");
                user.setName(userName);
                user.setPassWord(passWord);
                user.setUrl(urlStr);
                user.setPort(portStr);

                try {
                    user.setInterval(Integer.parseInt(intervalStr));
                    SettingWindow.this.parent.updateLoadingMessage("Saving user information...");
                    if (dbManager.getUser().isEmpty()) {
                        dbManager.insertIntoTable(DatabaseManager.USER_TABLE_NAME, value);
                    } else {
                        dbManager.updateTable(DatabaseManager.USER_TABLE_NAME,
                                dbManager.getUserTableInfo().getColumnNames(), value, "id='1'");
                    }
                    //save project and activity
                    if(user.getProjectCount()>0 && parent!=null) {
                        SettingWindow.this.parent.updateLoadingMessage("Saving project information...");
                        parent.loadProjectCombobox();
                        if (!dbManager.saveProjectAndActivity(user.getProjectList())) {
                            SettingWindow.this.parent.hideLoading();
                            JOptionPane.showMessageDialog(SettingWindow.this, "Could not save data because of Database error.", "Error",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                    SettingWindow.this.parent.updateLoadingMessage("Initializing Notification timer...");
                    parent.initNotificationTimer();
                    JOptionPane.showMessageDialog(SettingWindow.this, "Successfully save all data.");
                } catch (SQLException ex) {
        //            Logger.getLogger(SettingWindow.class.getName()).log(Level.SEVERE, null, ex);
                    JOptionPane.showMessageDialog(SettingWindow.this, "Could not save data because of Database error.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(SettingWindow.this, "Could not save data, please try again", "Error",
                            JOptionPane.ERROR_MESSAGE);
                } finally {
                    SettingWindow.this.parent.hideLoading();
                }
            }
        }).start();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
        this.updateInfo();
        if (this.urlStr.equals("") || this.userName.equals("") || this.passWord.equals("")) {
            JOptionPane.showMessageDialog(this, "Please fill all the text boxes with appropiate data.");
            return;
        }
        this.user.setName(this.userName);
        this.user.setPassWord(this.passWord);
        this.user.setUrl(this.urlStr);
        this.user.setPort(this.portStr);
        try {
            this.user.setInterval(Integer.parseInt(this.intervalStr));
        } catch (NumberFormatException ex) {
            Logger.getLogger(SettingWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.parent.showLoading("Please wait...", this);
        new Thread(new Runnable() {

            public void run() {
                TimeSheetClient tsClient = TimeSheetClient.getInstance();
                tsClient.setUser(user);
                SettingWindow.this.parent.updateLoadingMessage("Trying to login...");
                int loginRet = tsClient.logIn();
                if (loginRet == 0) {//wrong user name or password
                    SettingWindow.this.parent.hideLoading();
                    JOptionPane.showMessageDialog(SettingWindow.this, "Please give correct user name and password.",
                            "Wrong Username/Password", JOptionPane.ERROR_MESSAGE);
                    return;
                } else if (loginRet == -1) {
                    SettingWindow.this.parent.hideLoading();
                    JOptionPane.showMessageDialog(SettingWindow.this, "Server seem to be down or unreachable. Please make sure your "
                            + "server information are correct and save the configuration,\n later this system will try to connect to "
                            + "the server autometically to get necessary data.", "Server not found", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                boolean errorOccuer = false;
                if (tsClient.isLoggedIn()) {
                    SettingWindow.this.parent.updateLoadingMessage("Login successful, loading submit page");
                    String submitPage = tsClient.getSubmitPage("");
                    if (!submitPage.equals("")) {
                        SettingWindow.this.parent.updateLoadingMessage("Start JS and Html parsing...");
                        ParseSubmitPage parseSubmitPage = ParseSubmitPage.getInstance();
                        parseSubmitPage.setHtmlCode(submitPage);
                        try {
                            parseSubmitPage.parse(false, true);
                            SettingWindow.this.parent.updateLoadingMessage("Parsing complete...");
                            if (SettingWindow.this.user.replaceAllProject(parseSubmitPage.getProjects())) {
                                SettingWindow.this.updateComponetsFromDB();
                            } else {
                                errorOccuer = true;
                            }
                        } catch (Exception ex) {
                            errorOccuer = true;
                            ChronicleLogger.getInstance().logDebug("Page parsing error "+ex.getMessage());
                        }
                    } else {
                        ChronicleLogger.getInstance().logDebug("Couldn't retrieve the submit page");
                    }
                } else {
                    ChronicleLogger.getInstance().logDebug("Couldn't Logged In");
                }
                SettingWindow.this.parent.hideLoading();
                if (errorOccuer) {
                    JOptionPane.showMessageDialog(SettingWindow.this, "Unexpected error! Please try again.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                } else {
                    SettingWindow.this.parent.setProjectListSynchOnce(true);
                    JOptionPane.showMessageDialog(SettingWindow.this, 
                            "Successfully collect all data,\nPlease verify and save.", "Success",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        }).start();
        
    }//GEN-LAST:event_updateButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SettingWindow dialog = new SettingWindow(null, true, null, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JSlider intervalSlide;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree paTree;
    private javax.swing.JPasswordField passwordBox;
    private javax.swing.JTextField portBox;
    private javax.swing.JButton saveButton;
    private javax.swing.JButton updateButton;
    private javax.swing.JTextField urlBox;
    private javax.swing.JTextField userNameBox;
    // End of variables declaration//GEN-END:variables

    private void buildProjectAndActivityTree(ArrayList<Project> projectList) {
        ChronicleLogger.getInstance().logDebug("Building Tree");
        this.paTree.removeAll();

        DefaultTreeCellRenderer treeCellRenderer = new DefaultTreeCellRenderer();
        treeCellRenderer.setOpenIcon(null);
        treeCellRenderer.setClosedIcon(null);
        treeCellRenderer.setLeafIcon(null);

        paTree.setCellRenderer(treeCellRenderer);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Projects and Activities");
        if (projectList != null && !projectList.isEmpty()) {
            for (int i=0; i<projectList.size(); i++) {
                Project proj = projectList.get(i);
                if(proj.getName().equals("")) {
                    ChronicleLogger.getInstance().logDebug("Project Name Not found for: "+proj.getId());
                    projectList.remove(i);
                    i--;
                    continue;
                }
                DefaultMutableTreeNode projects = new DefaultMutableTreeNode(proj.getName());
                for (int j=0; j<proj.getActivityCount(); j++) {
                    DefaultMutableTreeNode activity = new DefaultMutableTreeNode(proj.getActivityAt(j).getName());
                    projects.add(activity);
                }
                root.add(projects);
            }
        }
        paTree.setModel(new javax.swing.tree.DefaultTreeModel(root));
    }

    private void updateComponetsFromDB() {
        if (this.user == null || this.user.getName().equals("")) {
            if (this.dbManager == null) {
                return;
            }
            this.userNameBox.setText("");
            this.passwordBox.setText("");
            this.urlBox.setText("196.35.231.10");
            this.portBox.setText("80");
            this.intervalSlide.setValue(2);

            this.buildProjectAndActivityTree(null);
        } else {
            this.userNameBox.setText(user.getName());
            this.passwordBox.setText(user.getPassWord());
            this.urlBox.setText(user.getUrl());
            this.portBox.setText(user.getPort());
            this.intervalSlide.setValue(user.getInterval() % 13);

            this.buildProjectAndActivityTree(user.getProjectList());
        }
    }
}
